package org.example.controller;

import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.example.controller.request.SendCodeRequest;
import org.example.enums.BizCodeEnum;
import org.example.enums.SendCodeEnum;
import org.example.service.NotifyService;
import org.example.util.CommonUtil;
import org.example.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/notify/v1")
@Slf4j
public class NotifyController {

    @Autowired
    private Producer captchaProducer;
    @Autowired
    private NotifyService notifyService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final long CAPTCHA_CODE_EXPIRATION_TIME = 1000 * 10 * 60;

    /**
     * 获取验证码
     *
     * @param request
     * @param response
     */
    @GetMapping("captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        String captchaText = captchaProducer.createText();
        log.info("验证码：{}", captchaText);

        //将验证码保存到redis中,设置过期时间
        redisTemplate.opsForValue().set(getCaptchaKey(request), captchaText, CAPTCHA_CODE_EXPIRATION_TIME, TimeUnit.MILLISECONDS);

        BufferedImage bufferedImage = captchaProducer.createImage(captchaText);
        try (ServletOutputStream outputStream = response.getOutputStream()) {
//            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(bufferedImage, "JPG", outputStream);
            outputStream.flush();
//            outputStream.close();新语法自动关闭
        } catch (IOException e) {
            log.info("获取验证码流异常：{}", e);
        }

    }

    public String getCaptchaKey(HttpServletRequest request) {
        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        String key = "account-service:captcha:" + CommonUtil.MD5(ip + userAgent);
        log.info("验证码key：{}", key);
        return key;
    }

    /**
     * 发送短信验证码接口
     *
     * @return
     */
    @PostMapping("send_code")
    public JsonData sendCode(@RequestBody SendCodeRequest sendCodeRequest, HttpServletRequest request) {

        String key = getCaptchaKey(request);
        String cacheCaptcha = redisTemplate.opsForValue().get(key);

        String captcha = sendCodeRequest.getCaptcha();

        if (cacheCaptcha != null && captcha != null && cacheCaptcha.equalsIgnoreCase(captcha)) {
            //成功
            redisTemplate.delete(key);
            JsonData jsonData = notifyService.sendCode(SendCodeEnum.USER_REGISTER, sendCodeRequest.getTo());
            return jsonData;
        } else {
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR);
        }

    }


//    /**
//     * 测试发送验证码接口-主要用于对比优化前后区别
//     * @return
//     */
//    @RequestMapping("send_code")
//    public JsonData sendCode() {
//        notifyService.textSendSms();
//        return JsonData.buildSuccess();
//    }
}
